package com.ns002.yigou.quote.common.connection;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ns002.yigou.quote.common.task.LoadRealTimeQuoteTask;
import com.ns002.yigou.quote.json.HuangJinQuote;
import com.ns002.yigou.quote.json.QueryQuote;
import com.opslab.util.StringUtil;
import okhttp3.*;
import okio.ByteString;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by xu on 2017/7/11 0011.
 * 外汇行情连接
 */
@Component
public class HuangJinQuoteConnection {

    @Autowired
    LoadRealTimeQuoteTask loadRealTimeQuoteTask;
    static Logger log = Logger.getLogger(HuangJinQuoteConnection.class);

    static String wsQuote = "ws://114.215.194.241:8188/hq?token="; //改成自已服务端的地址

    final static OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .readTimeout(10000, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(10000, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(10000, TimeUnit.SECONDS)//设置连接超时时间
            .addInterceptor(new ReceivedCookiesInterceptor())
            .build();
    static String hq_token = null;

    private void loadToken() {
        Request cookieRequest = new Request.Builder().url("http://www.dyhjw.com/meiyuanzhishu").build();

        try {
            mOkHttpClient.newCall(cookieRequest).execute().body();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void connection() {

        loadToken();

        log.error("加载webSocket:" + wsQuote + hq_token);
        Request quoteRequest = new Request.Builder().url(wsQuote + hq_token).build();
        mOkHttpClient.newWebSocket(quoteRequest, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("onOpen:");
            }

            @Override
            public void onMessage(WebSocket webSocket, String json) {
                List<HuangJinQuote> quotes = JSON.parseObject(json, new TypeReference<List<HuangJinQuote>>() {
                });
                for (int i = 0; i < quotes.size(); i++) {
                    if (!quotes.get(i).getC().equals("DINIW")) {   //只要美元指数
                        quotes.remove(i);
                        i--;
                    }
                }

                if (quotes.size() == 0) {
                    return;
                }

                if (quotes.size() > 1) {     //只要一天数据
                    quotes = quotes.subList(0, 1);
                }


                Map<String, QueryQuote> queryQuoteMap = new HashMap<>();
                for (HuangJinQuote quote : quotes) {
                    QueryQuote queryQuote = new QueryQuote();
                    queryQuote.setContract(quote.getC());
                    queryQuote.setCode(quote.getC());
                    queryQuote.setQuote(quote.getP());
                    queryQuote.setPreClose(quote.getLC());
                    queryQuote.setOpen(StringUtil.isEmpty(quote.getO()) ? quote.getLC() : quote.getO());
                    queryQuote.setNewDate(new Date(Long.parseLong(quote.getT() + "000")));
                    queryQuote.setCreateDate(new Date());

                    queryQuote.setyQuote(quote.getLC());
                    queryQuote.setHigh(quote.getH());
                    queryQuote.setLow(quote.getL());

                    queryQuoteMap.put(quote.getC(), queryQuote);
                }

                loadRealTimeQuoteTask.run(queryQuoteMap);

            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                System.out.println("onMessage2:" + bytes.string(Charset.defaultCharset()));
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("onClosing:");
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                System.out.println("onClosed:");
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.out.println("onFailure:");
                connection();
            }
        });

    }

    /**
     * 将服务器Cookies保存起来
     */
    static class ReceivedCookiesInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());

            if (!originalResponse.headers("Set-Cookie").isEmpty()) {

                for (String cookies : originalResponse.headers("Set-Cookie")) {

                    String[] cookie = cookies.split(";");
                    for (String string : cookie) {
                        if (string.startsWith("hq_Token=")) {
                            hq_token = URLDecoder.decode(string.replace("hq_Token=", ""), "UTF-8");
                        }
                    }


                }

            }

            return originalResponse;
        }
    }

}
